# coding=utf-8


from os import path
from Effects_Library_minWin import Ui_MainWindow
from PySide2.QtWidgets import QApplication, QWidget, QHBoxLayout, QVBoxLayout, QToolButton, QSizePolicy,QPushButton, QGroupBox, QGridLayout
from PySide2.QtGui import QIcon, QFont, QPixmap
from PySide2.QtCore import QPoint, QRect, QSize, Qt  # , pyqtSignal
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from PySide2 import QtWidgets,QtCore
from PySide2 import QtGui
#PySide2
#PyQt5
import sys
import os

import maya.mel as mel
from maya import OpenMayaUI as omui
from shiboken2 import wrapInstance
mayaMainWindowPtr = omui.MQtUtil.mainWindow()
mayaMainWindow = wrapInstance(long(mayaMainWindowPtr), QWidget)  # 鑾峰緱Maya涓荤獥鍙�

# 获取鼠标事件
class MyBtn(QToolButton):
    def __init__(self):
        super(MyBtn,self).__init__()
        self.Btn=super(MyBtn,self)
        self.setParent(mayaMainWindow)  # 灏嗘柊绐楀彛璁剧疆涓簃aya鐨勫瓙绾�
        self.setWindowFlags(Qt.Window)
    '''
    def mouseMoveEvent(self, e):
        print("ok")

    def mousePressEvent(self, e):
        print("Not Ok")'''

    def enterEvent(self, a0):
        self.setcoonton(self.Btn.text())
        return (self.Btn.enterEvent(a0))

    def leaveEvent(self, a0):
        files = os.listdir(self.Btn.text())
        img = QtGui.QImage(self.Btn.text() + "/" + files[self.n])  # 这里图片路径可以不给格式：QtGui.QImage(r'd:/test')
        pixmap = QtGui.QPixmap(img)
        fitPixmap = pixmap.scaled(140, 140, QtCore.Qt.IgnoreAspectRatio,QtCore.Qt.SmoothTransformation)  # 注意 scaled() 返回一个 QtGui.QPixmap
        icon = QtGui.QIcon(fitPixmap)
        self.Btn.setIcon(icon)
        self.Btn.setIconSize(QtCore.QSize(140, 140))
        #super().setFixedHeight(140)
        #super().setFixedWidth(140)
        self.timer1.stop()
        return self.Btn.leaveEvent(a0)

    def setcoonton(self, two_Level_path):
        self.Pic_Path = two_Level_path
        self.n = 0
        if self.n != 0:
            self.n == 0
        self.Timerrange = 50
        self.timer1 = QTimer()
        self.timer1.start(self.Timerrange)
        self.timer1.timeout.connect(lambda *args: self.timer_TimeOut(two_Level_path))

    def timer_TimeOut(self, two_Level_path):
        files = os.listdir(two_Level_path)
        if self.n < len(files):
            self.n = self.n + 1
        if self.n == len(files):
            self.n = 0

        img = QtGui.QImage(two_Level_path + "/" + files[self.n])  # 这里图片路径可以不给格式：QtGui.QImage(r'd:/test')
        pixmap = QtGui.QPixmap(img)
        fitPixmap = pixmap.scaled(200, 200, QtCore.Qt.IgnoreAspectRatio,QtCore.Qt.SmoothTransformation)  # 注意 scaled() 返回一个 QtGui.QPixmap
        icon = QtGui.QIcon(fitPixmap)
        self.Btn.setIcon(icon)
        self.Btn.setIconSize(QtCore.QSize(200, 200))

        #super().setIcon(QIcon(two_Level_path + "/" + files[self.n]))
        #super().setIconSize(QtCore.QSize(200, 200))
        ##super().setScaledContents(True)
        #super().setFixedHeight(200)
        #super().setFixedWidth(200)

class mainWindow(Ui_MainWindow, QMainWindow):

    def __init__(self):
        super(mainWindow, self).__init__()
        self.setParent(mayaMainWindow)  # 灏嗘柊绐楀彛璁剧疆涓簃aya鐨勫瓙绾�
        self.setWindowFlags(Qt.Window)
        self.setupUi(self)
        self.flowLayout = FlowLayout()
        self.Create_first_directory()
        # 鐩綍鐣岄潰璁剧疆
        self.treeView.header().setVisible(False)

        self.scrollArea.setWidgetResizable(True)
        self.pushButton.clicked.connect(self.ImportPic)

    def Create_first_directory(self):  # index鏄鐐瑰嚮鑺傜偣鐨勭储寮�
        self.projcet = 'D:/img/'
        self.model = QFileSystemModel()
        self.model.setRootPath(QDir.cleanPath(self.projcet))
        mf = self.model.setNameFilters(['*.txt'])

        self.treeView.setModel(self.model)
        self.treeView.setRootIndex(self.model.index(self.projcet))  # 鍙樉绀鸿缃殑閭ｄ釜鏂囦欢璺緞銆�
        self.treeView.clicked.connect(self.Onclicked)

    def Onclicked(self, index):
        for i in range(self.flowLayout.count()):
            self.flowLayout.itemAt(i).widget().deleteLater()
        fileName = self.model.fileName(index)
        filePath = self.model.filePath(index)
        # print(filePath,fileName)
        if os.path.isdir(filePath):
            for three_Level_Name in os.listdir(filePath):
                threePath = filePath + '/' + three_Level_Name
                if os.path.isdir(threePath):
                    self.Pic_button(threePath)
                    self.flowLayout.addWidget(self.button)
        self.listWidget.setLayout(self.flowLayout)


    def Pic_button(self, two_Level_path):
        self.button = MyBtn()
        #self.button = QToolButton()
        self.button.setText(two_Level_path)
        self.button.setObjectName(str(two_Level_path))

        if os.path.isdir(two_Level_path):
            if len(os.listdir(two_Level_path)) > 10:

                if os.path.isfile(two_Level_path + '/' + os.listdir(two_Level_path)[5]):
                    picPath = two_Level_path + '/' + os.listdir(two_Level_path)[5]
                    img = QtGui.QImage(picPath)  # 这里图片路径可以不给格式：QtGui.QImage(r'd:/test')
                    pixmap = QtGui.QPixmap(img)
                    fitPixmap = pixmap.scaled(140, 140, QtCore.Qt.IgnoreAspectRatio,QtCore.Qt.SmoothTransformation)  # 注意 scaled() 返回一个 QtGui.QPixmap
                    icon = QtGui.QIcon(fitPixmap)
                    self.button.setIcon(icon)
                    self.button.setIconSize(QtCore.QSize(140, 140))

                    '''
                    icon = QIcon()
                    icon.addFile(picPath, QSize(), QIcon.Normal, QIcon.Off)
                    self.button.setIcon(icon)
                    # 鍥剧墖澶у皬
                    self.button.setIconSize(QSize(140, 140))
                    '''
            if len(os.listdir(two_Level_path)) < 3 and len(os.listdir(two_Level_path)) < 8:
                if os.path.isfile(two_Level_path + '/' + os.listdir(two_Level_path)[4]):
                    picPath = two_Level_path + '/' + os.listdir(two_Level_path)[4]
                    img = QtGui.QImage(picPath)  # 这里图片路径可以不给格式：QtGui.QImage(r'd:/test')
                    pixmap = QtGui.QPixmap(img)
                    fitPixmap = pixmap.scaled(140, 140, QtCore.Qt.IgnoreAspectRatio,
                                              QtCore.Qt.SmoothTransformation)  # 注意 scaled() 返回一个 QtGui.QPixmap
                    icon = QtGui.QIcon(fitPixmap)
                    self.button.setIcon(icon)
                    self.button.setIconSize(QtCore.QSize(140, 140))

                    '''
                    icon = QIcon()
                    icon.addFile(picPath, QSize(), QIcon.Normal, QIcon.Off)
                    self.button.setIcon(icon)
                    # 鍥剧墖澶у皬
                    self.button.setIconSize(QSize(140, 140))'''
            if len(os.listdir(two_Level_path)) > 3:

                if os.path.isfile(two_Level_path + '/' + os.listdir(two_Level_path)[2]):
                    picPath = two_Level_path + '/' + os.listdir(two_Level_path)[2]
                    img = QtGui.QImage(picPath)  # 这里图片路径可以不给格式：QtGui.QImage(r'd:/test')
                    pixmap = QtGui.QPixmap(img)
                    fitPixmap = pixmap.scaled(140, 140, QtCore.Qt.IgnoreAspectRatio,
                                              QtCore.Qt.SmoothTransformation)  # 注意 scaled() 返回一个 QtGui.QPixmap
                    icon = QtGui.QIcon(fitPixmap)
                    self.button.setIcon(icon)
                    self.button.setIconSize(QtCore.QSize(140, 140))

                    '''
                    icon = QIcon()
                    icon.addFile(picPath, QSize(), QIcon.Normal, QIcon.Off)
                    self.button.setIcon(icon)
                    # 鍥剧墖澶у皬
                    self.button.setIconSize(QSize(140, 140))'''
        #self.button.setAutoDefault(True)
        self.button.clicked.connect(lambda *args: self.setcoonton(two_Level_path))

    def setcoonton(self, two_Level_path):
        self.Pic_Path = two_Level_path
        print(self.Pic_Path)
        self.n = 0
        if self.n != 0:
            self.n == 0
        self.Timerrange = 50
        self.timer1 = QTimer()
        self.timer1.start(self.Timerrange)
        self.timer1.timeout.connect(lambda *args: self.timer_TimeOut(two_Level_path))

    def timer_TimeOut(self, two_Level_path):
        files = os.listdir(two_Level_path)

        if self.n < len(files):
            self.n = self.n + 1
        if self.n == len(files):
            self.n = 0
        self.label.setPixmap(QPixmap(two_Level_path + "/" + files[self.n]))
        self.label.setScaledContents(True)
        self.label.setFixedHeight(200)
        self.label.setFixedWidth(200)


    def ImportPic(self):
        pic = os.listdir(self.Pic_Path)
        ImgFilePath = self.Pic_Path + '/' + pic[0]
        File = os.path.basename(ImgFilePath)
        (imgName, extension) = os.path.splitext(File)
        imgpolyPlane = []
        ListPolyPlanes = cmds.ls(transforms=1)
        for ListPolyPlane in ListPolyPlanes:
            # print ListPolyPlane
            if imgName in ListPolyPlane:
                # print ListPolyPlane
                for polyPlanes in cmds.listHistory(ListPolyPlane):
                    if 'polyPlane' in polyPlanes:
                        # print polyPlanes
                        imgpolyPlane.append(polyPlanes)  # print imgpolyPlane
        nub = ''
        for i in range(len(imgpolyPlane)):
            if i + 1 == len(imgpolyPlane):
                nub = str(i + 1)  # print imgName+nub  # imgName = imgName + str(i+1)

        polyP = cmds.polyPlane(n=imgName + nub, sx=1, sy=1)

        main_A = cmds.circle(n=imgName + 'main_A' + nub, nr=[0, 1, 0], sw=360, d=3, r=1.5, ut=0, ch=0, tol=0.01)[0]
        main_B = cmds.circle(n=imgName + 'main_B' + nub, nr=[0, 1, 0], sw=360, d=3, r=1, ut=0, ch=0, tol=0.01)[0]
        polyP_Grp = cmds.group(em=True, name=imgName + '_Grp' + nub)

        cmds.parent(main_B, main_A)
        cmds.parentConstraint(main_B, polyP[0])
        cmds.scaleConstraint(main_B, polyP[0], mo=1, weight=1)

        cmds.setAttr(polyP[0] + ".tx", lock=1)
        cmds.setAttr(polyP[0] + ".ty", lock=1)
        cmds.setAttr(polyP[0] + ".tz", lock=1)
        cmds.setAttr(polyP[0] + ".rx", lock=1)
        cmds.setAttr(polyP[0] + ".ry", lock=1)
        cmds.setAttr(polyP[0] + ".rz", lock=1)
        cmds.setAttr(polyP[0] + ".sx", lock=1)
        cmds.setAttr(polyP[0] + ".sy", lock=1)
        cmds.setAttr(polyP[0] + ".sz", lock=1)
        cmds.setAttr(polyP[0] + ".v", lock=1)

        cmds.parent(polyP[0], main_A, polyP_Grp)

        CvMin = '|' + polyP_Grp + '|' + main_A
        cmds.addAttr(CvMin, ln='ShiJianPanYi', at='long', dv=0)
        cmds.setAttr(CvMin + '.ShiJianPanYi', e=1, keyable=1)

        cmds.addAttr(CvMin, ln='BaoGuang', at='float', min=-5, max=5, dv=0)
        cmds.setAttr(CvMin + '.BaoGuang', e=1, keyable=1)

        cmds.addAttr(CvMin, ln='TouMingTongDao', at='float', min=0, max=2, dv=1)
        cmds.setAttr(CvMin + '.TouMingTongDao', e=1, keyable=1)

        cmds.addAttr(CvMin, ln='ColorGainR', at='float', min=0, max=20, dv=0)
        cmds.setAttr(CvMin + '.ColorGainR', e=1, keyable=1)
        cmds.addAttr(CvMin, ln='ColorGainG', at='float', min=0, max=20, dv=0)
        cmds.setAttr(CvMin + '.ColorGainG', e=1, keyable=1)
        cmds.addAttr(CvMin, ln='ColorGainB', at='float', min=0, max=20, dv=0)
        cmds.setAttr(CvMin + '.ColorGainB', e=1, keyable=1)

        lambertName = cmds.shadingNode('lambert', asShader=True, n=polyP[0] + '_labt')
        lambertSG = cmds.sets(renderable=1, noSurfaceShader=1, empty=1, name=polyP[0] + '_SG')
        cmds.connectAttr(lambertName + '.outColor', lambertSG + '.surfaceShader', f=1)
        cmds.sets(polyP[0], e=1, forceElement=lambertSG)
        shadingNodefile = cmds.shadingNode('file', asTexture=1, isColorManaged=1, n=polyP[0] + '_file')
        cmds.connectAttr(shadingNodefile + '.outColor', lambertName + '.color', f=1)

        TextureName = cmds.shadingNode('place2dTexture', asUtility=1, n=polyP[0] + '_Texture')
        Nodes = ['coverage', 'translateFrame', 'rotateFrame', 'mirrorU', 'mirrorV', 'stagger', 'wrapU',
                 'wrapV', 'repeatUV', 'offset', 'rotateUV', 'noiseUV', 'vertexUvOne', 'vertexUvTwo',
                 'vertexUvThree', 'vertexCameraOne']
        for Node in Nodes:
            cmds.connectAttr(TextureName + '.' + Node, shadingNodefile + '.' + Node, f=1)
        cmds.connectAttr(TextureName + '.outUV', shadingNodefile + '.uv')
        cmds.connectAttr(TextureName + '.outUvFilterSize', shadingNodefile + '.uvFilterSize')

        cmds.setAttr(shadingNodefile + '.fileTextureName', ImgFilePath, type="string")
        cmds.defaultNavigation(force=1, connectToExisting=1, source=shadingNodefile, destination=lambertName + '.color')
        cmds.connectAttr(shadingNodefile + '.outTransparency', lambertName + '.transparency', f=1)
        cmds.select(shadingNodefile, r=1)
        # 璐村浘婊氬姩

        visible = cmds.workspaceControl('AttributeEditor', q=1, visible=1)
        if visible:
            cmds.workspaceControl('AttributeEditor', e=1, close=1)

        mel.eval("ToggleAttributeEditor")

        cmds.setAttr(shadingNodefile + ".useFrameExtension", 1)

        cmds.connectAttr(main_A + '.ShiJianPanYi', shadingNodefile + '.io', f=1)
        cmds.connectAttr(main_A + '.BaoGuang', shadingNodefile + '.exp', f=1)
        cmds.connectAttr(main_A + '.TouMingTongDao', shadingNodefile + '.ag', f=1)

        cmds.connectAttr(main_A + '.ColorGainR', shadingNodefile + '.cor', f=1)
        cmds.connectAttr(main_A + '.ColorGainG', shadingNodefile + '.cog', f=1)
        cmds.connectAttr(main_A + '.ColorGainB', shadingNodefile + '.cob', f=1)
        cmds.evalDeferred('mel.eval("ToggleChannelsLayers")')


class FlowLayout(QLayout):
    def __init__(self, parent=None, margin=0, spacing=-1):
        super(FlowLayout, self).__init__(parent)

        if parent is not None:
            self.setContentsMargins(margin, margin, margin, margin)

        self.setSpacing(spacing)

        self.itemList = []

    def __del__(self):
        item = self.takeAt(0)
        while item:
            item = self.takeAt(0)

    def addItem(self, item):
        self.itemList.append(item)

    def count(self):
        return len(self.itemList)

    def clear(self):  # real signature unknown; restored from __doc__
        """ clear(self) -> None """
        self.itemList.clear()

    def itemAt(self, index):
        if index >= 0 and index < len(self.itemList):
            return self.itemList[index]

        return None
    def deleteLater(self): # real signature unknown; restored from __doc__
        """ deleteLater(self) """
        pass
    def takeAt(self, index):
        if index >= 0 and index < len(self.itemList):
            return self.itemList.pop(index)

        return None

    def expandingDirections(self):
        return Qt.Orientations(Qt.Orientation(0))

    def hasHeightForWidth(self):
        return True

    def heightForWidth(self, width):
        height = self.doLayout(QRect(0, 0, width, 0), True)
        return height

    def setGeometry(self, rect):
        super(FlowLayout, self).setGeometry(rect)
        self.doLayout(rect, False)

    def sizeHint(self):
        return self.minimumSize()

    def minimumSize(self):
        size = QSize()

        for item in self.itemList:
            size = size.expandedTo(item.minimumSize())

        margin, _, _, _ = self.getContentsMargins()

        size += QSize(2 * margin, 2 * margin)
        return size

    def doLayout(self, rect, testOnly):
        x = rect.x()
        y = rect.y()
        lineHeight = 0

        for item in self.itemList:
            wid = item.widget()
            spaceX = self.spacing() + wid.style().layoutSpacing(QSizePolicy.PushButton,
                                                                QSizePolicy.PushButton, Qt.Horizontal)
            spaceY = self.spacing() + wid.style().layoutSpacing(QSizePolicy.PushButton,
                                                                QSizePolicy.PushButton, Qt.Vertical)
            nextX = x + item.sizeHint().width() + spaceX
            if nextX - spaceX > rect.right() and lineHeight > 0:
                x = rect.x()
                y = y + lineHeight + spaceY
                nextX = x + item.sizeHint().width() + spaceX
                lineHeight = 0

            if not testOnly:
                item.setGeometry(QRect(QPoint(x, y), item.sizeHint()))

            x = nextX
            lineHeight = max(lineHeight, item.sizeHint().height())

        return y + lineHeight - rect.y()


if __name__ == '__main__':
    #app = QApplication(sys.argv)
    mainWindow = mainWindow()
    mainWindow.show()
    #sys.exit(app.exec_())